package com.bestv.bsr.core.service.impl.jt.remote.fallback;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bestv.bsr.core.context.RecommendContext;
import com.bestv.bsr.core.context.RecommendContextHolder;
import com.bestv.bsr.core.service.impl.jt.dto.response.JTTopicResponseDto;
import com.bestv.remote.context.MethodContext;
import com.bestv.remote.context.ParamContext;
import com.bestv.remote.context.ServerContext;
import com.bestv.remote.interfaces.BlockHandler;
import com.bestv.remote.interfaces.FallbackHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import static com.bestv.bsr.core.constants.CacheConstants.JT_BACK_UP;

/**
 * 九天 主题推荐 降级处理
 *
 * @author taojiacheng
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class JiuTianTopicFallbackHandler implements FallbackHandler<JTTopicResponseDto>, BlockHandler<JTTopicResponseDto> {

    private final RedissonClient redissonClient;

    @Override
    public JTTopicResponseDto handlerFallback(ServerContext serverContext, MethodContext methodContext,
                                              ParamContext paramContext, Throwable throwable) {
        log.warn("九天 主题推荐 接口 进入降级处理流程,{},{}", serverContext, methodContext);
        return doFallback(serverContext, methodContext);
    }


    @Override
    public JTTopicResponseDto handlerBlock(ServerContext serverContext, MethodContext methodContext,
                                           ParamContext paramContext, BlockException blockException) {
        log.warn("九天 主题推荐 接口 进入熔断处理流程,{},{}", serverContext, methodContext);
        return doFallback(serverContext, methodContext);
    }

    private JTTopicResponseDto doFallback(ServerContext serverContext, MethodContext methodContext) {
        RecommendContext recommendContext = RecommendContextHolder.getRecommendContext();
        if (recommendContext != null) {
            String cacheKey = String.format(JT_BACK_UP, recommendContext.getSceneId(), recommendContext.getItemTypes().get(0));
            RBucket<JTTopicResponseDto> bucket = redissonClient.getBucket(cacheKey);
            JTTopicResponseDto jtTopicResponseDto = bucket.get();
            log.info("九天主题推荐接口, 读取缓存备份结果: {}", jtTopicResponseDto);
            return jtTopicResponseDto;
        }
        // 备份的时候不允许降级
        throw new RuntimeException("九天主题推荐接口备份失败");
    }

}
